import { saveOrder } from '../api/pay'

interface PreOrder {
	appId: string;
	nonceStr: string;
	packageVal: string;
	paySign: string;
	signType: string;
	timeStamp: string;
}

const pay = ({ productId = 0 }: { productId: Number }) => {
	return new Promise(async (resolve, rejects) => {
		try{
			const res: { result: PreOrder } = await saveOrder({ productId })
			const { timeStamp, signType, paySign, packageVal, nonceStr } = res.result
			uni.requestPayment({
				timeStamp: String(timeStamp), // 时间戳（单位：秒）
				nonceStr, // 随机字符串
				package: packageVal, // 预支付交易订单号
				signType, //固定值
				paySign, //签名
			    success(res: PlusPaymentPaymentResult) {
					console.log('支付成功回调', res)
					resolve(res)
				},
			    fail(e: PaymentValidationErrors) {
					rejects(e)
				}
			} as any)
		} catch(err) {
			rejects(err)
		}
	})
}

export function usePayment() {
	return {
		pay
	}
}